#include <iostream>
#include <mosquittopp.h>

class SubscribeClient : public mosqpp::mosquittopp
{
public:
    SubscribeClient(const char *id, const char *host, int port)
        : mosquittopp(id), host_(host), port_(port) {}

    bool connect()
    {
        int rc = mosquittopp::connect(host_.c_str(), port_, 60);
        return rc == MOSQ_ERR_SUCCESS;
    }

    void subscribe(const std::string &topic)
    {
        int rc = mosquittopp::subscribe(nullptr, topic.c_str());
        if (rc == MOSQ_ERR_SUCCESS)
        {
            std::cout << "Subscribed to topic: " << topic << std::endl;
        }
        else
        {
            std::cerr << "Failed to subscribe to topic: " << topic << std::endl;
        }
    }

protected:
    virtual void on_connect(int rc) override
    {
        std::cout << "Connected with code " << rc << std::endl;
    }

    virtual void on_subscribe(int mid, int qos_count, const int *granted_qos) override
    {
        std::cout << "Subscribed with message ID: " << mid << std::endl;
    }

    virtual void on_message(const struct mosquitto_message *message) override
    {
        std::cout << "Message received on topic: " << message->topic << std::endl;
        std::cout << "Message payload: " << std::string(static_cast<const char *>(message->payload), message->payloadlen) << std::endl;
    }

private:
    std::string host_;
    int port_;
};

int main()
{
    mosqpp::lib_init();

    SubscribeClient client("subscribe_client", "127.0.0.1", 1883);
    if (client.connect())
    {
        client.subscribe("test/topic");
    }

    while (true)
    {
        client.loop(1000);
    }

    mosqpp::lib_cleanup();

    return 0;
}